
<!--上传图片组件 -->
<template>
    <div>
      <el-upload
        class="upload-demo"
        ref="upload"
        :action="fileServer"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :file-list="fileList"
        :auto-upload="false"
        :list-type="listType"
        :multiple="true"
        :on-success="uploadSuccess"
        :on-error="uploadError"
        :http-request="uploadFile"
        :disabled="imgFlag"
        :limit="limit"

      >

        <el-button slot="trigger" size="small" type="primary" >{{upType}}</el-button>
<!--        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>-->
        <div slot="tip" class="el-upload__tip">{{tip}}</div>

      </el-upload>
    </div>
</template>

<script>
  /**
   * 参考文件发送代码 https://www.jianshu.com/p/c662daa6bc77
   * 多文件上传代码 https://blog.csdn.net/weixin_43915587/article/details/91953230
   */
  import {ResultStatus} from "../views/constant/ResultStatus";
  import {StringUtil} from "../utils/StringUtil";
  import moment from 'moment'
  export default {
    props:{
      'upType':String,//上传内容类型的提示
      'imgFlag':Boolean,
      "limit":Number,//限制上传的张数
      "listType":String,//文件类型
      "tip":String,

    },
    data() {
      return {


        imgUrl:'',//文件返回地址
        fileData: '',  // 文件上传数据（多文件合一）
        serverUrl: this.$axios.defaults.fileServer+'/file/upload/bbs' ,//文件上传地址
        uploadUrl: this.$axios.defaults.uploadUrl ,//文件上传地址
        baseURL:this.$axios.defaults.baseURL,//服务器地址
        fileList: [],
          //[{name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}, {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}]
        fileServer:this.$axios.defaults.fileServer,
      };
    },
    methods: {
         submitUpload  :async function() {
        // if (this.fileList.length === 0) {
        //   this.$message({
        //     message: '请先选择文件',
        //     type: 'warning'
        //   })
        //   return;
        // }

        this.fileData = new FormData();  // new formData对象
        this.$refs.upload.submit();  // 提交调用uploadFile函数

        let config = {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        };

        var self = this;
        let date = moment().format('YYYYMMDD');
       await this.$axios.post(this.uploadUrl+date, this.fileData, config).then(
          (response)=>{
            let datas = response.data;
            if(datas.code != ResultStatus.SUCCESS){
             this.$notify( StringUtil.warning( datas.msg));
              return;
            }

            this.imgUrl = datas.data;
            StringUtil.checkNull(this.imgUrl);


          }
        ).catch(function (error) {
            StringUtil.warning(error.data.data);
        })
        console.log(this.imgUrl)
        this.$emit('func',this.imgUrl)

      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      uploadSuccess(res, file) {
        console.log(123)
        console.log(res)
        // res为图片服务器返回的数据
        // 获取富文本组件实例

        // 如果上传成功
        if (res.status == 1001) {

        }
      },
      // 富文本图片上传失败
      uploadError() {
        // loading动画消失
        this.quillUpdateImg = false;
        this.$message.error("图片插入失败");
      },
      // 上传文件
      uploadFile(file) {
        this.fileData.append('files', file.file);  // append增加数据
      },
      /**
       * 接收图片
       * @param data
       */
      receiveFileList(data) {
        if(StringUtil.checkNull(data)){
          return;
        }
       let imgs =  data.split("&&");
       let imgArray  = new Array();
        for(let i = 0;i<imgs.length;i++){
          if(StringUtil.checkNull(imgs[i])){
            continue;
          }
          let fullName  = "";
          let imgsArray = imgs[i].split(".");
          //文件名拆分 后缀
          if(imgsArray.length > 1) {
            let suffix = imgsArray[imgsArray.length-1];
            let prefixArray = imgsArray[0].split("\\");
            let prefix = prefixArray[prefixArray.length - 1];
             fullName = prefix + "." + suffix;
          }
          imgArray[i] = {name:fullName,url:this.fileServer+imgs[i]};
        }

        this.fileList  = imgArray;
      }
    }
  }
</script>
